/*jslint browser: true*/
/*global $, jQuery, alert, window*/
window.view = {
    "major_id": function (id_num) {
        "use strict";
        if (id_num) {
            $("#major_selection option[value=" + id_num + "]")[0].selected = true;
        }
        return parseInt($("#major_selection").val(), 10);
    },
    "char_id_list": function (char_id_list) {
        "use strict";
        var question_data,
            treeObj,
            index,
            length,
            char_option_list,
            char_item;
        if (char_id_list) {
            question_data = window.format.s2c(window.storage(window.question_key),
                                              window.format.question)[0];
            treeObj = window.zTree || $.fn.zTree.getZTreeObj("treeDemo");
            length = question_data.char_id_list.length;
            for (index = 0; index < length; index = index + 1) {
                treeObj.checkNode(treeObj.getNodeByParam("id", question_data.char_id_list[index]));
            }
            window.sync.charChecked_ztree_select();
        } else {
            char_id_list = [];
            char_option_list = $("#char_selection").children();
            length = char_option_list.length;
            for (index = 0; index < length; index = index + 1) {
                char_item = char_option_list[index];
                char_id_list.push(parseInt(char_item.value, 10));
            }
            return char_id_list;
        }
    },
    "main_description": function (value_str) {
        "use strict";
        if (value_str) {
            $("#description").val(value_str);
        }
        return window.trim($("#description").val());
    },
    "category_num": function (value_str) {
        "use strict";
        if (value_str) {
            $("#category option[value=" + value_str + "]")[0].selected = true;
        }
        return parseInt($("#category").val(), 10);
    },
    "level_num": function (value_str) {
        "use strict";
        if (value_str) {
            $("#level option[value=" + value_str + "]")[0].selected = true;
        }
        return parseInt($("#level").val(), 10);
    },
    "sub_body": function (value_str) {
        "use strict";
        if (value_str) {
            $("#q_body").val(value_str);
        }
        return window.trim($("#q_body").val());
    },
    "sub_image_id": function (id_value) {
        "use strict";
        if (id_value) {
            $("#upload_image").attr("href", "/link/" + id_value + "/image/")
                    .attr("name", id_value)
                    .html("图片链接,点击可查看");
            $("#upload_loading").hide();
            $("#upload_control").hide();
            $("#upload_result").show();
        } else {
            return parseInt($("#upload_image").attr("name"), 10) || 0;
        }
    },
    "sub_options": function (value_str) {
        "use strict";
        if (value_str) {
            $("#q_options").val(value_str);
        }
        return window.trim($("#q_options").val());
    },
    "sub_options_count": function (count_num) {
        "use strict";
        if (count_num) {
            $("#options_count option[value=" + count_num + "]")[0].selected = true;
        }
        return parseInt($("#options_count").val(), 10);
    },
    "sub_analysis": function (value_str) {
        "use strict";
        if (value_str) {
            $("#q_analysis").val(value_str);
        }
        return window.trim($("#q_analysis").val());
    },
    "sub_answer": function (value_str) {
        "use strict";
        if (value_str) {
            $("#q_answer option[value=" + value_str + "]")[0].selected = true;
        }
        var q_answer = $("#q_answer").val();
        return q_answer instanceof Array ? q_answer.join("") : q_answer;
    }
};
window.sync = {
    "major_data_option": function () {
        "use strict";
        var optionList = [],
            major_all_key = window.major_all_key,
            major_all_list = window.format.s2c(window.storage(major_all_key),
                                                window.format.major),
            index,
            length = major_all_list.length,
            item;
        for (index = 0; index < length; index = index + 1) {
            item = major_all_list[index];
            optionList.push('<option id="');
            optionList.push("major_" + item.id);
            optionList.push('" value="');
            optionList.push(item.id);
            optionList.push('">');
            optionList.push(item.name);
            optionList.push('</option>');
        }
        $(optionList.join("")).appendTo("#major_selection");
    },
    "char_data_ztree": function () {
        "use strict";
        var major_id = window.view.major_id(),
            char_list_key = '/major/{major_id}/char/'.format({major_id: major_id}),
            char_list = window.fetchData(window.storage(char_list_key), window.format.char),
            index,
            length = char_list.length,
            char_item,
            zNodes = [],
            setting = {
                check: { enable: true  },
                data: {
                    simpleData: { enable: true }
                }
            };
        /*
            data :[ { "id": 1, "name":"", "father_id":0, "is_kp":false, "listorder":""}, 
                    { "id": 2, "name":"", "father_id":0, "is_kp":false, "listorder":""},]}
        zNodes =[   { id:13, pId:1, name:"禁止拖拽 1-3", isParent:true },
                    { id:131, pId:13, name:"禁止拖拽 1-3-1", isParent:true },]
        }*/
        for (index = 0; index < length; index = index + 1) {
            char_item = char_list[index];
            zNodes.push({
                id : char_item.id,
                pId : char_item.father_id,
                name : char_item.name,
                isParent : !char_item.is_kp,
                nocheck: !char_item.is_kp,
                open: true
            });
        }
        $.fn.zTree.init($("#treeDemo"), setting, zNodes);
        window.zTree = $.fn.zTree.getZTreeObj("treeDemo");
    },
    "charChecked_ztree_select" : function () {
        "use strict";
        var treeObj = window.zTree || $.fn.zTree.getZTreeObj("treeDemo"),
            nodes = treeObj.getCheckedNodes(true),
            optionList = [],
            index = 0,
            length = nodes.length,
            item,
            name,
            id;
        for (index = 0; index < length; index = index + 1) {
            item = nodes[index];
            name = item.id  + " - " + item.name + ",";
            id = "char_" + item.id;
            optionList.push('<option id="');
            optionList.push(id);
            optionList.push('" value="');
            optionList.push(item.id);
            optionList.push('">');
            optionList.push(name);
            optionList.push('</option>');
        }
        $("#char_selection").html("");
        $(optionList.join("")).appendTo("#char_selection");
        $("#zTreeContainer").hide("normal");
    },
    "question_data_html": function () {
        "use strict";
        var question_data = window.format.s2c(window.storage(window.question_key),
                                              window.format.question)[0];
        //major
        window.view.major_id(question_data.major_id);
        window.sync.char_data_ztree();
        //char
        window.view.char_id_list(question_data.char_id_list);
        //category
        window.view.category_num(question_data.category_num);
        //level
        window.view.level_num(question_data.level_num);
        //description
        window.view.main_description(question_data.description);
        /**sub*/
        window.view.sub_body(question_data.body);
        window.view.sub_image_id(question_data.image_id);
        window.view.sub_options(question_data.options);
        window.view.sub_options_count(question_data.options_count);
        window.view.sub_analysis(question_data.analysis);
        window.view.sub_answer(question_data.answer);
    }
};
window.init = {
    "global_var": function () {
        "use strict";
        window.major_all_key = "/major/";
        var category_list = window.category_list,
            level_list = window.level_list,
            pathname = location.pathname,
            update_reg = new RegExp('^/manager/question/(' + category_list.join("|") + ')/([0-9])+/$'),
            reg_result_list = update_reg.exec(pathname);
        if (reg_result_list) {
            //update question
            window.is_update = true;
            window.question_id = parseInt(reg_result_list[2], 10);
            window.question_type = reg_result_list[1];
            window.question_key = "/question/{id}/".format({id: window.question_id});
            window.zTree = null;
        } else {
            window.is_update = false;
        }
    },
    "url_varify": function () {
        "use strict";
        if (window.is_update) {
            var question_key = window.question_key,
                question_data = window.format.s2c(window.storage(question_key),
                                                  window.format.question)[0],
                question_type = window.question_type,
                varify_type = window.category_list.getNameByNum(question_data.category_num),
                url = "/manager/question/{type}/{id}/".format({
                    type: varify_type,
                    id: window.question_id
                });
            if (varify_type !== question_type) {
                window.location.assign(url);
            }
        }
    },
    "html_title": function () {
        "use strict";
        if (window.is_update) {
            $(".edit_type").each(function () {
                $(this).html("编辑");
            });
        }
    },
    "zTree_position": function () {
        "use strict";
        var aOffset = $("#char_selection").offset();
        $("#zTreeContainer").css("top", aOffset.top + "px");
        $("#zTreeContainer").css("left", aOffset.left + "px");
        $("#zTreeContainer").css("width", $("#char_selection").width() + "px");
    },
    "char_ztree": function () {
        "use strict";
        window.sync.char_data_ztree();
        window.sync.charChecked_ztree_select();
    },
    "major_select": function () {
        "use strict";
        window.sync.major_data_option();
    },
    "question_html": function () {
        "use strict";
        if (window.is_update) {
            window.sync.question_data_html();
        }
    },
    "addEventListener": function () {
        "use strict";
        $("#char_selection").click(window.listener.char_select_show);
        $("#zTreeContainer").mouseleave(window.sync.charChecked_ztree_select);
        $("#major_selection").change(function () {
            window.sync.char_data_ztree();
            window.sync.charChecked_ztree_select();
        });
        $("#upload_file").click(window.listener.image_upload);
        $("#upload_file_change").click(window.listener.image_upload_again);
        $("#create_question").click(function () {
            if (window.is_update) {
                window.listener.update_question();
            } else {
                window.listener.create_question();
            }
        });
        window.hideLoading();
    }
};
window.init_func_list = ["global_var",
                         "url_varify",
                         "html_title",
                         "major_select",
                         "zTree_position",
                         "char_ztree",
                         "question_html",
                         "addEventListener"];

function getChangedValue() {
    "use strict";
    var transFormat = {
            "main_major_id": "major_id",
            "main_category_num": "category_num",
            "main_level_num": "level_num",
            "main_description": "description",
            "main_char_id_list": "char_id_list",

            "hat_image_id": "hat_image_id",
            "hat_body_text": "hat_body_text",

            "sub_image_id": "image_id",
            "sub_options_count": "options_count",
            "sub_answer": "answer",
            "sub_analysis": "analysis",
            "sub_body": "body",
            "sub_options": "options"
        },
        question_key = window.question_key,
        jsData = {
            "major_id": window.view.major_id(),
            "category_num": window.view.category_num(),
            "level_num": window.view.level_num(),
            "description": window.view.main_description(),
            "char_id_list": window.view.char_id_list(),
            "image_id": window.view.sub_image_id(),
            "options_count": window.view.sub_options_count(),
            "answer": window.view.sub_answer(),
            "analysis": window.view.sub_analysis(),
            "body": window.view.sub_body(),
            "options": window.view.sub_options()
        },
        serverData = window.storage(question_key),
        transData = {},
        server_var_name,
        js_var_name,
        server_var,
        js_var;
    for (server_var_name in transFormat) {
        if (transFormat.hasOwnProperty(server_var_name)) {
            js_var_name = transFormat[server_var_name];
            js_var = jsData[js_var_name];
            server_var = serverData[server_var_name];
            if (server_var instanceof Array) {
                if (server_var.toString() !== js_var.toString()) {
                    transData[js_var_name] = js_var;
                }
            } else {
                if (server_var !== js_var) {
                    transData[js_var_name] = js_var;
                }
            }
        }
    }
    return transData;
}

window.listener = {
    "image_upload": function () {
        "use strict";
        if ($("#upload_file_input").val()) {
            $("#upload_loading").show();
            $.ajaxFileUpload({
                url: '/link/upload/',
                secureuri: false,
                fileElementId: 'upload_file_input',
                dataType: 'json',
                data: {
                    name: $("#file_description").val()
                },
                async: false,
                success: function (result, status) {
                    var image_id = result.id;
                    window.view.sub_image_id(image_id);
                }
            });
        }
    },
    "image_upload_again": function () {
        "use strict";
		$("#upload_control").show();
		$("#upload_result").hide();
        $("#upload_result a").attr("href", "")
            .attr("name", "")
            .html("");
    },
    "create_question": function () {
        "use strict";
        window.loading();
        var question_data = {
            "major_id": window.view.major_id(),
            "category_num": window.view.category_num(),
            "level_num": window.view.level_num(),
            "description": window.view.main_description(),
            "char_id_list": window.view.char_id_list(),
            "image_id": window.view.sub_image_id(),
            "options_count": window.view.sub_options_count(),
            "answer": window.view.sub_answer(),
            "analysis": window.view.sub_analysis(),
            "body": window.view.sub_body(),
            "options": window.view.sub_options()
        };
        $.ajax({
            url: "/question/",
            type: "POST",
            data: JSON.stringify(question_data),
            dataType: "json",
            async: true,
            success: function (result, status) {
                var question_data = window.format.s2c(result.data,
                                                      window.format.question)[0],
                    question_id = question_data.id,
                    question_key = "/question/{id}/".format({id: question_id}),
                    url = "/manager/question/{type}/{id}/".format({
                        type: window.category_list.getNameByNum(question_data.category_num),
                        id: question_id
                    });
                window.storage(question_key, result.data);
                window.location.assign(url);
            }
        });
    },
    "update_question": function () {
        "use strict";
        window.loading();
        var question_key = window.question_key,
            transData = window.getChangedValue();
        $.ajax({
            url: question_key,
            type: "PUT",
            data: JSON.stringify(transData),
            dataType: "json",
            async: true,
            success: function (result, status) {
                var question_key = window.question_key,
                    saved_question_data = window.storage(question_key)[0],
                    response_data = result.data[0],
                    question_data = window.format.s2c(result.data, window.format.question)[0],
                    url = "/manager/question/{type}/{id}/".format({
                        type: window.category_list.getNameByNum(question_data.category_num),
                        id: question_data.id
                    }),
                    item_name;
                window.storageRemove(question_key);
                for (item_name in response_data) {
                    if (response_data.hasOwnProperty(item_name)) {
                        saved_question_data[item_name] = response_data[item_name];
                    }
                }
                window.storage(question_key, [saved_question_data]);
                window.location.assign(url);
            }
        });
    },
    "char_select_show": function () {
        "use strict";
        if ($("#treeDemo").children().length) {
            $("#char_selection").blur();
            $("#zTreeContainer").show("normal");
        }
    }
};
